using AutoMapper;
using MediatR;
using ThreeTeams.Domain.ThreeTeams.Domain.Entities;
using WMS.Api.Application.Commands;
using WMS.Common;
using WMS.Infrastructure;

namespace WMS.Api.Application.CommandHandlers
{
    /// <summary>
    /// 更新产品命令处理程序
    /// </summary>
    public class UpdateProductCommandHandler : IRequestHandler<UpdateProductCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Product> _productRepository;
        private readonly IMapper _mapper;

        public UpdateProductCommandHandler(IBaseRepository<Product> productRepository, IMapper mapper)
        {
            _productRepository = productRepository;
            _mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(UpdateProductCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>("更新产品");

            try
            {
                // 检查产品是否存在
                var existingProduct = await _productRepository.GetValueByIdAsync(request.Product.Id);
                if (existingProduct == null)
                {
                    result.code = StatusCodeEnum.DataNotExist;
                    result.msg = "产品不存在";
                    return result;
                }

                // 检查SKU是否已被其他产品使用
                var skuProduct = await _productRepository.GetNewValueAsync(p => p.SKU == request.Product.SKU && p.Id != request.Product.Id);
                if (skuProduct != null)
                {
                    result.code = StatusCodeEnum.DataExist;
                    result.msg = $"SKU '{request.Product.SKU}' 已被其他产品使用";
                    return result;
                }

                // 更新产品
                _mapper.Map(request.Product, existingProduct);
                var affectedRows = await _productRepository.UpdateNewAsync(existingProduct);

                result.Success(affectedRows);
            }
            catch (Exception ex)
            {
                result.code = StatusCodeEnum.Fail;
                result.msg = $"更新产品失败：{ex.Message}";
            }

            return result;
        }
    }
} 